import {fetchClassification} from '../../../services/classification/fetchClassification';
import { uploadPictures, createReviews, updateImages } from '../../../services/reviews/createReviews';
const app = getApp();
const baseUrl = app.globalData.BaseUrl;

Page({
  data: {
    newReviewsID: '',
    uploading: false,
    classifictionList: {},
    areaText: '',
    groupChain: '',
    defaultRate: 3.5,
    mark: 3.5,
    title: '',
    content: '',
    areaValue: [],
    aspects: [],
    areas: [],
    entitys: [],
    areaVisible: false,
    rateVisible: false,
    maxUpdateNumber: 9,
    originFiles: [],
    tmpFiles: [],
    uploadFilesName: [],
    gridConfig: {
      column: 5,
      width: 120,
      height: 120,
    },
    config: {
      count: 1,
    },
    uploadSizeConfig: {
      size: 2,
      unit: 'MB',
      message: '单图片大小不可超过 2 MB'
    },
    authData: {
      user_id: wx.getStorageSync('user_id'),
      reviews_author: wx.getStorageSync('nickName'),
      reviews_avatar: wx.getStorageSync('avatarUrl')
    },
    submitPopVisible: false,
    closeOverlayOn: false, 
    popupLoading: true,
    popupLoadingHidden: false,
    popupResultHidden: true,
    resultState: {
      theme: 'success',
      title: '提交成功！'
    }
  },

  getClassifications() {
    fetchClassification().then((data) => {
      // setTimeout(() => {
        this.setData({
          classifictionList: data,
          aspects: data.aspects,
          areas: this.getOptions(data.areas, (area) => this.match(area.value, data.aspects[0].value, 2)),
          entitys: this.getOptions(data.entitys, (entity) => this.match(entity.value, data.areas[0].value, 4))
        });
      // }, 0)
    });
  },

  getOptions(res, filter) {
    if (filter) {
      return res.filter(filter);
    }
  
    return res;
  },

  match(v1, v2, size) {
    return v1.toString().slice(0, size) === v2.toString().slice(0, size);
  },
  
  onLoad() {
    this.init();
  },

  init() {
    this.getClassifications();
  },

  getAreas(aspectsValue) {
    const { classifictionList } = this.data;
    const areas =  this.getOptions(classifictionList.areas, (area) => this.match(area.value, aspectsValue, 2));
    const entitys = this.getEntitys(areas[0].value);

    // this.setData({ areas, entitys });

    return { areas, entitys };
  },

  getEntitys(areasValue) {
    const { classifictionList } = this.data;

    return this.getOptions(classifictionList.entitys, (entity) => this.match(entity.value, areasValue, 4));
  },

  onTitleChange(e) {
    const { value } = e.detail;
    this.setData({
      title: value,
    });
  },

  onContentChange(e) {
    const {value} = e.detail;
    this.setData({
      content: value,
    });
  },

  onColumnChange(e) {
    const { column, index } = e.detail;
    const { aspects, areas } = this.data;

    if (column === 0) {
      // 更改一级
      const { areas, entitys } = this.getAreas(aspects[index].value);

      this.setData({ areas, entitys });
    }

    if (column === 1) {
      // 更改二级
      const entitys = this.getEntitys(areas[index].value);

      this.setData({ entitys });
    }

    if (column === 2) {
      // 更改叶子
    }
  },

  onPickerChange(e) {
    const { value, label } = e.detail;

    console.log('picker confirm:', e.detail);
    this.setData({
      areaVisible: false,
      areaValue: value,
      groupChain: label.join(' '),
      rateVisible: true,
    });
  },

  onPickerCancel(e) {
    console.log('picker cancel', e.detail);
    this.setData({
      areaVisible: false,
    });
  },

  onAreaPicker() {
    this.setData({ areaVisible: true });
  },

  onMarkChange(e) {
    const {value} = e.detail;
    this.setData({
      mark: value
    })
  },

  handleSuccess(e) {
    const { files } = e.detail;
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },

  handleAddImages(e) {
    // console.log(e, 'upload....');
    const { files } = e.detail;
    this.setData({
      tmpFiles: files,
    });
  },

  async handleRelease(e) {
    const createDataform = this.data;
    if(this.validateForm(createDataform)) {
      this.setData({
        uploading: true,
      });
      // todo 开始上传表单操作
      const createData = {
        reviews_title: createDataform.title,
        reviews_content: createDataform.content,
        user_id: createDataform.authData.user_id,
        reviews_author: createDataform.authData.reviews_author,
        reviews_avatar: createDataform.authData.reviews_avatar,
        group_chain: createDataform.groupChain,
        reviews_group_code: createDataform.areaValue[2],
        mark: createDataform.mark,
        liker_num: 0,
        is_release: true
      };

      this.popupSubmitBlock();

      // 创建点评记录
      await this.onCreateReviews(createData);
      // 上传图片
      await this.onUploadImages(createDataform.tmpFiles, this.data.newReviewsID);
      // 将图片名称保存至数据库
      await this.onPushImages(this.data.uploadFilesName, this.data.newReviewsID);
    }
    this.setData({
      uploading: false,
    });
    console.log("::created::");
  },

  validateForm(formData) {
    if(!formData.title) {
      wx.showToast({
        title: "在标题处写点什么吧",
        icon: "none",
        duration: 3000
      });
      return false;
    }
    if(!formData.content) {
      wx.showToast({
        title: "在正文处写点什么吧",
        icon: "none",
        duration: 3000
      });
      return false;
    }
    if(!formData.groupChain) {
      wx.showToast({
        title: "去选择一个要点评的实体吧",
        icon: "none",
        duration: 3000
      });
      return false;
    }
    if(formData.tmpFiles.length <= 0) {
      wx.showToast({
        title: "无图无真相哦！亲",
        icon: "none",
        duration: 3000
      });
      return false;
    }

    return true;
  },

  async onUpload(dataForm, reviews_id='265045bc-0295-411e-af9b-a2d9a73c23e4') {
    const tmpFiles = dataForm.tmpFiles;
    const authData = this.authData;
    // console.log(tmpFiles, '::files::');
    // console.log(authData, '::authData::');
    

    const resultNames = [];
    await tmpFiles.forEach((fileItem, index, arr) => {
      uploadPictures(fileItem, reviews_id).then((data) => {
        resultNames.push(data);
      });
    });

    this.setData({
      uploadFilesName: resultNames
    });
    
    return ;
  }, 

  async onCreateReviews(formData) {
    console.log('Create Reviews starts');
    // 以下为同步处理
    await new Promise(resolve => setTimeout(() => {
      createReviews(formData).then((data) => {
        const newReviewsID = data;
        if (!!newReviewsID) {
          this.setData({
            newReviewsID
          });
        }
        resolve(newReviewsID);
      });
    }, 1000));// 模拟耗时操作
    console.log('Create Reviews ends');
  },

  async onUploadImages(files, reviewsId) {
    console.log(files, 'Upload Images starts');
    // 以下为同步处理
    await new Promise(resolve => setTimeout(() => {
      const resultNames = [];
      files.forEach((fileItem, index, arr) => {
        uploadPictures(fileItem, reviewsId).then((data) => {
          resultNames.push(data);
        });
      });

      this.setData({
        uploadFilesName: resultNames
      });
      resolve(resultNames);
    }, 3000)); // 模拟耗时操作
    console.log('Upload Images ends');
  },

  async onPushImages(filenames, reviewsID) {
    console.log('Push Images starts');
    // 以下为同步处理
    await new Promise(resolve => setTimeout(() => {
      // 上传图片验证，全部成功后，再进行表单更新，失败则回滚数据库。注意要给用户反馈通知。
      // todo 选主图要另外实现，现在没想好
      const imagesData = {
        reviews_id: reviewsID,
        primary_image: filenames[0],
        reviews_images: filenames,
        is_release: true
      };
      updateImages(imagesData).then((data) => {
        const { reviews_id } = data;
        if (!!reviews_id) {
          // todo 跳转到不带返回按钮的结果页
          console.log(reviews_id, "::success::");
        }
        resolve(reviews_id);
      });
    }, 1000)); // 模拟耗时操作
    console.log('Push Images ends');
  },

  handleJoinBox(e) {
    this.popupSubmitBlock();
  },

  popupSubmitBlock() {
    this.setData({ 
      submitPopVisible: true,
    });
    setTimeout(() => {
      this.setData({
        popupLoading: false,
        popupLoadingHidden: true,
        popupResultHidden: false
      })
    }, 5000);
  },

  onVisibleChange(e) {
    return ;
  },

  handleResultGohome(e) {
    this.resetFormData();

    wx.switchTab({
      url: `/pages/home/home`,
    });
  },

  resetFormData() {
    this.setData({
      newReviewsID: '',
      uploading: false,
      areaText: '',
      groupChain: '',
      mark: 3.5,
      title: '',
      content: '',
      areaValue: [],
      areaVisible: false,
      rateVisible: false,
      originFiles: [],
      tmpFiles: [],
      submitPopVisible: false,
      closeOverlayOn: false, 
      popupLoading: true,
      popupLoadingHidden: false,
      popupResultHidden: true,
    })
  }

});